package com.umfwechat.lightprogram.controller.pos;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umfwechat.lightprogram.controller.selfdeploy.MerchantJoinController;
import com.umfwechat.lightprogram.controller.selfdeploy.ShowImgController;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.SaasPropertyUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.operation.common.ReqMessage;
import com.umpay.operation.common.ResMessage;
import com.umpay.operation.model.saas.StoreLictype;
import com.umpay.operation.service.saas.TStoreLictypeServiceRemote;

/**
 * POS相关图片上传删除Controller	上传图片、删除图片
 * @author ChenFuLong 2017-12-14
 * 
 */
@Controller
@RequestMapping("/newMerchantProductDeploy")
public class PosImageController {
	
	private static Logger logger = LoggerFactory.getLogger(PosImageController.class);

	@Resource
	private TStoreLictypeServiceRemote tStoreLictypeServiceRemote;
	
/* + + + + + + + + + + + + + + + + + + + + + + + + + + + 上传图片 + + + + + + + + + + + + + + + + + + + + + + + + + + + */
	
	@RequestMapping(value="/uploadImg", produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject uploadImg(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception{
		logger.info("----#---------#--【上传POS相关照片】，开始--#---------#--");
		JSONObject resultJson = new JSONObject();
		String reqJSON = (String) request.getAttribute("_requestData");
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "照片上传失败");
			logger.error("【上传POS相关照片】数据转换异常", e);
			return resultJson;
		}
		//~~~~~~ 获取数据信息 ~~~~~~
		String imgHttpUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","img.http.url", "");	//获取图片服务器Http地址
		String imgFileUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","saasPlat.comp.uploadPath", "");	//获取图片服务器存储地址
		logger.info("----#---------#--【获取照片上传地址】HTTP：" + imgHttpUrl + "，File：" + imgFileUrl);
		if(StringUtil.isEmpty(imgHttpUrl) || StringUtil.isEmpty(imgFileUrl)){	//获取配置信息失败则返回提示信息
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "照片上传失败");
			return resultJson;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();	//创建一个DiskFileItemFactory工厂  
		ServletFileUpload upload = new ServletFileUpload(factory);	//创建一个文件上传解析器  
		upload.setHeaderEncoding("UTF-8");
		FileItem file = null;	//图片
		String img = (String) json.get("imgName");	//图片标识（资质类型编号）
		String storeId = (String) json.get("storeId");	//店铺编号
		//~~~~~~ 生成一些必要的信息 ~~~~~~
		String imgName = UUID.randomUUID().toString().replace("-", "") + ".jpg";	//生成图片名称
		String imageUrl = imgFileUrl + storeId + "/" + imgName;	//生成图片的URL（路径：配置文件中的路径 + 店铺编号 + 文件名名称）
		List<FileItem> items = upload.parseRequest(request);	//得到FileItem的集合items
		for (FileItem item : items) {
			String name = item.getFieldName();
			if ("file".equals(name)) {
				file = item;
			}
		}
		if (StringUtil.isEmpty(img) || StringUtil.isEmpty(storeId) || file == null) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "请求参数不足");
			return resultJson;
		}
		//~~~~~~ 开始上传照片 ~~~~~~
		logger.info("【将图片存入服务器并返回URL】开始");
		String imgUrl = ShowImgController.getImgUrl(file, imageUrl, imgHttpUrl);
		logger.info("【将图片存入服务器并返回URL】结束" + imgUrl);
		if(StringUtil.isEmpty(imgUrl)){
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "图片上传失败");
			return resultJson;
		}
		//~~~~~~ 将数据存储（更新）到店铺资质表 ~~~~~~
		ReqMessage req = ReqMessageUtil.makeOpReq();
		ResMessage res = new ResMessage();
		req.put("storeId",storeId);	//店铺编号
		req.put("lictypeId",img);	//资质类型编号
		try {
			logger.info("【获取店铺资质】请求参数：" + req);
			res = tStoreLictypeServiceRemote.queryLictypeByPri(req);
			logger.info("【获取店铺资质】返回参数：" + res);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			logger.error("【获取店铺资质】异常", e);
			return resultJson;
		}
		if (!"0000".equals(res.getRetCode())) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			return resultJson;
		}
		StoreLictype storeLictype = (StoreLictype) res.getResMap().get("storeLictype");
		if (null != storeLictype) {	//不为空就更新
			storeLictype.setLictypePath(imgName);	//资质文件名称
			storeLictype.setLicfileState("01");	//状态：注册
			storeLictype.setIntime(null);;
			storeLictype.setModtime(null);
			Map<String, Object> storeLictypeMap = SaasPropertyUtil.javaBeanToMapO(storeLictype);
			req = ReqMessageUtil.makeOpReq();
			req.putAll(storeLictypeMap);
			try {
				logger.info("【更新店铺资质】请求参数：" + req);
				res = tStoreLictypeServiceRemote.updateLictypeByPri(req);
				logger.info("【更新店铺资质】返回参数：" + res);
			} catch (Exception e) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "服务器异常，请稍后再试");
				logger.error("【更新店铺资质】异常", e);
				return resultJson;
			}
			if (!"0000".equals(res.getRetCode())) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "图片上传失败");
				return resultJson;
			}
		}else {	//为空就插入
			req = ReqMessageUtil.makeOpReq();
			req.put("storeId",storeId);	//商户编号
			req.put("lictypeId",img);	//资质类型编号
			req.put("lictypePath",imgName);	//资质文件名称
			req.put("licfileState","01");	//状态：注册
			try {
				logger.info("【插入店铺资质】请求参数：" + req);
				res = tStoreLictypeServiceRemote.insertStoreLictype(req);
				logger.info("【插入店铺资质】返回参数：" + res);
			} catch (Exception e) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "服务器异常，请稍后再试");
				logger.error("【插入店铺资质】异常", e);
				return resultJson;
			}
			if (!"0000".equals(res.getRetCode())) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "图片上传失败");
				return resultJson;
			}
		}
		
		resultJson.put("retMsg", "成功");
		resultJson.put("retCode", "0000");
		resultJson.put("imgUrl", imgUrl);
		return resultJson;
	}



/* + + + + + + + + + + + + + + + + + + + + + + + + + + + 删除图片 + + + + + + + + + + + + + + + + + + + + + + + + + + + */

	@RequestMapping(value="/deleteImg", produces="application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject deleteImg(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception{
		logger.info("----#---------#--【删除POS相关照片】，开始--#---------#--");
		JSONObject resultJson = new JSONObject();
		String reqJSON = (String) request.getAttribute("_requestData");
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "照片删除失败");
			logger.error("【删除POS相关照片】数据转换异常", e);
			return resultJson;
		}
		String img = (String) json.get("imgName");	//图片标识（资质类型编号）
		String storeId = (String) json.get("storeId");	//店铺编号
		
		ReqMessage req = ReqMessageUtil.makeOpReq();
		ResMessage res = new ResMessage();
		req.put("storeId",storeId);	//店铺编号
		req.put("lictypeId",img);	//资质类型编号
		try {
			logger.info("【获取店铺资质】请求参数：" + req);
			res = tStoreLictypeServiceRemote.queryLictypeByPri(req);
			logger.info("【获取店铺资质】返回参数：" + res);
		} catch (Exception e) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "服务器异常，请稍后再试");
			logger.error("【获取店铺资质】异常", e);
			return resultJson;
		}
		if (!"0000".equals(res.getRetCode())) {
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "图片删除失败");
			return resultJson;
		}
		StoreLictype storeLictype = (StoreLictype) res.getResMap().get("storeLictype");
		if (null != storeLictype) {
			storeLictype.setLicfileState("02");	//注销
			storeLictype.setIntime(null);;
			storeLictype.setModtime(null);
			Map<String, Object> storeLictypeMap = SaasPropertyUtil.javaBeanToMapO(storeLictype);
			req = ReqMessageUtil.makeOpReq();
			req.putAll(storeLictypeMap);
			try {
				logger.info("【更新店铺资质】请求参数：" + req);
				res = tStoreLictypeServiceRemote.updateLictypeByPri(req);
				logger.info("【更新店铺资质】返回参数：" + res);
			} catch (Exception e) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "服务器异常，请稍后再试");
				logger.error("【更新店铺资质】异常", e);
				return resultJson;
			}
			if (!"0000".equals(res.getRetCode())) {
				resultJson.put("retCode", "0001");
				resultJson.put("retMsg", "图片上传失败");
				return resultJson;
			}
		}
		
		resultJson.put("retMsg", "成功");
		resultJson.put("retCode", "0000");
		return resultJson;
	}
}